import Icon from "@/components/Icon";
import Input from "@/components/Input";
import NavBar from "@/components/NavBar";
import React, { useEffect, useRef, useState } from "react";
import styles from "./index.module.scss";
import io, { Socket } from "socket.io-client";
import { useAppSelector } from "@/hooks";

export default function Chat() {
  // 聊天记录
  const [msgList, setMsgList] = useState<{ type: string; text: string }[]>([
    // 放两条初始消息
    // { type: "robot", text: "亲爱的用户您好，小智同学为您服务。" },
    // { type: "user", text: "你好" },
    // { type: "user", text: "你好" },
    // { type: "user", text: "你好" },
    // { type: "user", text: "你好" },
    // { type: "robot", text: "亲爱的用户您好，小智同学为您服务。" },
    // { type: "robot", text: "亲爱的用户您好，小智同学为您服务。" },
    // { type: "robot", text: "亲爱的用户您好，小智同学为您服务。" },
    // { type: "robot", text: "亲爱的用户您好，小智同学为您服务。" },
    // { type: "user", text: "你好" },
    // { type: "user", text: "你好" },
  ]);

  const { auth } = useAppSelector((state) => state.user);

  // 输入框的数据
  const [message, setMessage] = useState("");

  // ref  缓存 客户端 socket 实例
  const clientRef = useRef<Socket>();

  // 获取当前页面 根标签
  const chatRootRef = useRef<HTMLDivElement>({} as HTMLDivElement);

  useEffect(() => {
    // 创建 客户端实例
    const client = io("http://toutiao.itheima.net", {
      transports: ["websocket"], // 使用websocket 来和服务端对接 polling 长轮询 - http 可以向下兼容
      // 查询参数 token
      query: {
        token: auth.token,
      },
    });

    // 监听 连接成功
    client.on("connect", () => {
      // console.log("连接成功啦");
      setMsgList((msgList) => [
        ...msgList,
        { type: "robot", text: "我现在恭候着您的提问" },
      ]);
    });

    // 监听 服务器返回的消息
    client.on("message", ({ msg }) => {
      // 把响应的消息 插入到聊天界面上
      setMsgList((msgList) => [
        ...msgList,
        {
          type: "robot",
          text: msg,
        },
      ]);
    });

    // 存储 客户端实例
    clientRef.current = client;
  }, []);

  // 按下回车 发送消息
  const onSendMessage = (ev: React.KeyboardEvent) => {
    /* 
    1 判断按下的是不是  回车键 
    2 通过socket 来发送消息给后端 
    3 把发送的消息也存到 消息列表数组中，页面出现 我们发送的消息记录
    4 清空 输入框 
     */

    if (ev.key === "Enter") {
      clientRef.current?.emit("message", {
        msg: message,
        timestamp: Date.now(),
      });

      setMsgList((msgList) => [...msgList, { type: "user", text: message }]);

      setMessage("");
    }
  };

  // 监听消息数组，设置页面的滚动条 实时显示最新的聊天内容
  useEffect(() => {
    window.scrollTo({ left: 0, top: chatRootRef.current.offsetHeight });
  }, [msgList]);

  return (
    <div className={styles.root} ref={chatRootRef}>
      {/* 顶部导航栏 */}
      {/* <NavBar fixed={true}>小智同学</NavBar> */}
      <NavBar fixed>小智同学</NavBar>
      {/* <NavBar>小智同学</NavBar> */}

      {/* 聊天记录列表 */}
      <div className="chat-list">
        {/* 机器人的消息 */}
        {msgList.map((v, i) => (
          <div key={i}>
            {v.type === "robot" && (
              <div className="chat-item">
                <Icon type="iconbtn_xiaozhitongxue" />
                <div className="message">{v.text}</div>
              </div>
            )}
            {v.type === "user" && (
              <div className="chat-item user">
                <img
                  src={"http://toutiao.itheima.net/images/user_head.jpg"}
                  alt=""
                />
                <div className="message">{v.text}</div>
              </div>
            )}
          </div>
        ))}
      </div>

      <div className="footer">
        {/* 底部消息输入框 */}
        <div className="input-footer">
          <Input
            className="no-border"
            placeholder="请描述您的问题"
            value={message}
            onChange={(ev) => setMessage(ev.target.value)}
            onKeyUp={onSendMessage}
          />
          <Icon type="iconbianji" />
          <span className="send">发送</span>
        </div>
      </div>
    </div>
  );
}
